package admin

import (
	"errors"
	"fmt"
	"parking-lot-go-admin/model"
	"time"
)

type AdminAuthRuleStruct struct {
	Id         int       `json:"id" gorm:"type:int(11) auto_increment; NOT NULL; primary_key"`
	ParentId   int       `json:"parent_id" gorm:"type:int(11); COMMENT:'上级id'"`
	Level      int       `json:"level" gorm:"type:int(11); COMMENT:'当前层级'"`
	Path       string    `json:"path" gorm:"type:varchar(255); COMMENT:'路由地址'"`
	Name       string    `json:"name" gorm:"type:varchar(255); COMMENT:'路由名字'"`
	Component  string    `json:"component" gorm:"type:varchar(255); COMMENT:'按需加载需要展示的页面'"`
	Title      string    `json:"title" gorm:"type:varchar(255); COMMENT:'菜单名称'"`
	ShowParent int       `json:"show_parent" gorm:"type:tinyint(1);COMMENT:'显示父级'"`
	Icon       string    `json:"icon" gorm:"type:varchar(255)"`
	Rank       int       `json:"rank" gorm:"type:int(11);COMMENT:'1级路由生效'"`
	ShowLink   int       `json:"show_link" gorm:"type:tinyint(1);COMMENT:'是否在菜单中显示'"`
	CreatedAt  time.Time `json:"created_at" gorm:"type:datetime"`
	UpdatedAt  time.Time `json:"updated_at" gorm:"type:datetime"`
}

func (c *AdminAuthRuleStruct) TableName() string {
	return "admin_auth_rule"
}

func (c *AdminAuthRuleStruct) Insert(data AdminAuthRuleStruct) error {
	var adminAuthRuleStruct AdminAuthRuleStruct
	level := 0
	if data.ParentId > 0 {
		if err := model.Db.Table(c.TableName()).Where("id", data.ParentId).First(&adminAuthRuleStruct).Error; err != nil {
			return errors.New(fmt.Sprintf("查询父级失败,%s", err.Error()))
		}
		level = adminAuthRuleStruct.Level + 1
	}

	data.Level = level
	data.CreatedAt = time.Now()
	data.UpdatedAt = time.Now()

	if err := model.Db.Table(c.TableName()).Debug().Create(&data).Error; err != nil {
		return errors.New(fmt.Sprintf("插入数据失败,%s", err.Error()))
	}
	return nil
}

func (c *AdminAuthRuleStruct) Update(data AdminAuthRuleStruct) error {
	var adminAuthRuleStruct AdminAuthRuleStruct
	level := 0
	if data.ParentId > 0 {
		if err := model.Db.Table(c.TableName()).Where("id", data.ParentId).First(&adminAuthRuleStruct).Error; err != nil {
			return errors.New(fmt.Sprintf("查询父级失败,%s", err.Error()))
		}
		level = adminAuthRuleStruct.Level + 1
	}

	data.Level = level

	data.UpdatedAt = time.Now()

	if err := model.Db.Table(c.TableName()).Debug().Updates(&data).Error; err != nil {
		return errors.New(fmt.Sprintf("插入数据失败,%s", err.Error()))
	}
	return nil
}
